﻿namespace Pibby.Core.Feeds
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;

    public class ItemCollection : Collection<Item>
    {
        #region Constructors

        public ItemCollection()
            : base()
        {
            this.MostRecentDate = DateTime.MinValue;
            this.OldestDate = DateTime.MaxValue;
        }

        public ItemCollection(IList<Item> items)
            : base(items)
        {
            this.MostRecentDate = DateTime.MinValue;
            this.OldestDate = DateTime.MaxValue;
        }

        #endregion Constructors

        #region Properties

        public DateTime OldestDate
        {
            get;
            private set;
        }

        public DateTime MostRecentDate
        {
            get;
            private set;
        }

        #endregion Properties

        #region Overrides

        protected override void InsertItem(int index, Item item)
        {
            base.InsertItem(index, item);
            this.CheckPublicationDate(item);
        }

        #endregion Overrides

        private void CheckPublicationDate(Item item)
        {
            this.MostRecentDate = ItemCollection.Max(item.PublicationDate, this.MostRecentDate);
            this.OldestDate = ItemCollection.Min(item.PublicationDate, this.OldestDate);
        }

        private static DateTime Min(DateTime first, DateTime second)
        {
            if (first > second)
                return second;

            return first;
        }

        private static DateTime Max(DateTime first, DateTime second)
        {
            if (first < second)
                return second;

            return first;
        }

    }

}
